using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using MvcDemo.Db;
using MvcDemo.Models;
using MvcDemo.Repost;
using System.Linq;
using MvcDemo.Request;
namespace MvcDemo.Controllers
{
    public class ProductController:Controller
    {
        private readonly EfRepost<Product> _proRep=new EfRepost<Product>();
        public IActionResult Index()
        {
            var _CateRep=new EfRepost<Category>();
            var Cate=_CateRep.Table.Where(x=>x.IsDeleted==false).FirstOrDefault();
            if(Cate==null){
                _CateRep.Insert(new Category{
                    CategoryName="手机"
                });
            }

           
                  _proRep.Insert(new Product{
                ProductName="手机",
                Supplier="我是初始数据",
                Price=111,
                Stock=100,
                Remarks="我是备注",
                DisplayOrder=0,
                Creator=0,
                CategoryId=1
            });


          


         IList<Product> products=_proRep.Table.Where(x=>x.IsDeleted==false).ToList();
             
            return View(products);
        }


        public IActionResult CreateOrEdit(int id)
        {
             if(id==0){
                 return View();
             }else{
                 var products=_proRep.Table.Where(x=>x.Id==id).FirstOrDefault();
                 return View(products);
             }
        }

        public IActionResult BaoCun(productParm request)
        {
            if(request.Id==0){
                _proRep.Insert(new Product{
                    ProductName=request.ProductName,
                    Supplier=request.Supplier,
                    Price=request.Price,
                    Stock=request.Stock,
                    DisplayOrder=0,
                    Creator=0,
                    CategoryId=1,
                    Remarks=request.Remarks,
                });
            }else{
                var product=_proRep.Table.Where(x=>x.Id==request.Id).FirstOrDefault();
                product.ProductName=request.ProductName;
                product.Supplier=request.Supplier;
                product.Price=request.Price;
                product.Stock=request.Stock;
                product.Remarks=request.Remarks;
                _proRep.Update(product);
            }
            return Ok();
        }    

        public IActionResult Query(QueryParm request)
        {
            var product=_proRep.Table.Where(x=>x.IsDeleted==false && x.ProductName.Contains(request.KeyWork)).ToList();
            return Json(product);
        }

        public IActionResult Delete(int id)
        {
            _proRep.Delete(id);
            return RedirectToAction("Index");
        }

    }
}